﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using XCommunity.Users;
using System.Security.Principal;
using XCommunity.Frames;

namespace XCommunity.Forums
{
  internal class ConstraintConfig : IControlConstraint
  {

    public ConstraintConfig( XElement configuration )
    {
      Configuration = configuration;
    }

    public XElement Configuration
    {
      get;
      private set;
    }


    #region IControlConstraint 成员

    public bool IsSatisfied( IPrincipal user, string verb, params object[] frameObjects )
    {

      if ( verb != Configuration.Attribute( "verb" ).Value )
        return false;

      var topicElement = Configuration.Element( ForumsSystem.XF + "topic" );
      if ( topicElement != null )
      {
        var topic = frameObjects.OfType<ITopicFrame>().Single();

        if ( !EqualsUsername( user.Identity, topic.Meta.Launcher, topicElement.Attribute( "launcher" ) ) )
          return false;
      }


      var postElement = Configuration.Element( ForumsSystem.XF + "post" );
      if ( postElement != null )
      {
        var post = frameObjects.OfType<IPostFrame>().Single();

        if ( !EqualsUsername( user.Identity, post.Author, postElement.Attribute( "author" ) ) )
          return false;

        var themeAttribute = postElement.Attribute( "theme" );
        if ( themeAttribute != null )
        {
          bool themeSetting = bool.Parse( themeAttribute.Value );
          if ( post.IsTheme != themeSetting )
            return false;
        }
      }


      return true;

    }

    protected bool EqualsUsername( IIdentity currentLogged, string username, XAttribute setting )
    {
      if ( setting == null )
        return true;

      var usernameSetting = setting.Value;
      if ( usernameSetting == "#current-logged" )
        usernameSetting = currentLogged.Name;

      return string.Equals( username, usernameSetting, StringComparison.InvariantCultureIgnoreCase );
    }

    #endregion
  }
}
